<template>
  <cus-skeleton :loading="loading">
    <cus-form ref="formRef" :nodes="controls" />
  </cus-skeleton>
</template>

<script lang="ts">
import { ref } from 'vue'
import $ from '$';
import { useStore } from 'vuex';

export default {
  props: ['questions', 'id'],
  setup(props) {
    let store = useStore();

    let controls = ref([
      { label: '试卷名称', key: 'title', type: 'input', rule: { required: 'true', message: '请输入试卷名称' } },
      { label: '学科', key: 'hide', type: 'input', disabled: true, default: store.getters.subject.name, rule: { required: 'true' } },
      { label: '年级', key: 'gradeId', type: 'select', options: [], rule: { required: 'true', message: '请选择年级' } },
      { label: '年份', key: 'year', type: 'select', options: [], rule: { required: 'true', message: '请选择年份' } },
      { key: 'subjectId', type: 'hidden', default: store.getters.subject.code },
    ]);

    let loading = ref(true);
    let userId = store.getters.userInfo.user.id;
    let subjectCode = store.getters.subject.code;
    $.http.post('/permission/user/userDataRules', { userId, subjectCode }).then(res => {
      controls.value[2].options = res.json.grades
      controls.value[3].options = res.json.years
      loading.value = false;
    })

    let formRef = ref();

    const save = (resolve, reject) => {
      formRef.value.validate(async valid => {
        let paperChapters = props.questions!.reduce((group, node: any) => {
          let index = group.findIndex((n: any)=> n.title === node.questionTypeName)
          if (index > -1) {
            group[index].questions.push({ score: 0, subjectId: node.subjectId, questionId: node.id });
          } else {
            group[group.length] = {
              avgScore: 0,
              totalScore: 0,
              title: node.questionTypeName,
              questions: [{ score: 0, subjectId: node.subjectId, questionId: node.id }]
            }
          }
          return group;
        }, [] as any[])
        let params = {
          ...valid,
          sourceFrom: 4,
          paperChapters,
          totalScore: 0,
          isPublic: 1,
          questionCount: paperChapters.length
        }
        let res = await $.http.json('/tiku/paper/addPaper', params);
        if (res.result) {
          await $.http.post('/admin/questionImportLog/bindQuestionImportLogPaper', { importLogId: props.id, paperId: res.json.id })
          resolve(res)
        } else {
          reject();
        }
      })
    }
    return { controls, loading, formRef, save }
  }
}
</script>
